#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import urllib2

from model_gcm_2 import *
from google.appengine.ext import ndb
from model_PC import PC
from model_child import Child
from model_parent import Parent
from model_message import Message
from model_att import Att
from google.appengine.api import mail

API_KEY = "AIzaSyAM1_Z2K9Ga9WeIXXV9cRymAuf2jF5GFc8"





class GCM (ndb.Model):
    """ Models an individual parent id and his registration id """

    reg_id = ndb.StringProperty()
    parent_id = ndb.StringProperty()

    @staticmethod
    def create_new_register_id_by_parent_id(data_json):
        """ Create a new entity with registration id linked with parent id """
        data = json.loads(data_json)
        parent_id_given = data.get('parent_email_address')
        new_ent = GCM(reg_id = data.get('reg_id'),
                      parent_id = parent_id_given)
        check_entity_exists = GCM.query(GCM.parent_id == parent_id_given).get()
        if check_entity_exists is not None:
            ndb.Key(GCM, int(check_entity_exists.key.id())).delete()
        return new_ent.put()

    @staticmethod
    def delete_reg_id_by_parent_email_address(data_json):
        """ Delete the registration id of parent with given email address """
        data = json.loads(data_json)
        parent_id_given = data.get('parent_email_address')
        check_entity_exists = GCM.query(GCM.parent_id == parent_id_given).get()
        if check_entity_exists is not None:
            ndb.Key(GCM, int(check_entity_exists.key.id())).delete()
            return 1
        return 0

    @staticmethod
    def get_reg(childs_ids):
        list_regs_ids = []
        list_no_regs = {}
        for child_id_given in childs_ids:
            parents_list = PC.get_parents_id_by_child_id(child_id_given)
            for parent_id in parents_list:
                ent = ndb.gql("SELECT * FROM GCM WHERE parent_id IN (:mail)", mail=parent_id).fetch()
                if len(ent) == 0:
                    list_no_regs[parent_id] = child_id_given
                else:
                    for e in ent:
                        list_regs_ids.append(e.reg_id)
        return list_regs_ids, list_no_regs


    @staticmethod
    def send_arriving_att_to_parents(data_json):
        """ get a list of children ids, retrieve reg. ids and send an arriving message """
        # get list of children ids of given kindergarten
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        all_childs_ids = Child.get_children_in_KG_id(given_KG_id)
        childs_ids_arrived = []
        # childs_ids_not_arrived = []
        for c in all_childs_ids:
            d = {"child_id": c, "date": data.get("date")}
            d_j = json.dumps(d)
            if (Att.get_att_of_child_by_child_id_and_date(d_j) == 1):
                childs_ids_arrived.append(c)
        x = GCM2(API_KEY, "https://android.googleapis.com/gcm/send")

        value = GCM.get_reg(childs_ids_arrived)
        regs_ids = value[0]
        parents_no_regs_ids = value[1]
        data = {}
        if regs_ids is not None:
            for r_id in regs_ids:
                c_id = GCM.get_child_id_by_reg_id(reg_id_given=r_id, given__KG_id=given_KG_id)
                # c_id = regs_ids[r_id]
                info_j = Child.get_child_info(c_id)
                c_info = json.loads(info_j)
                tu = (c_id, c_info.get("gender"), (c_info.get("first_name").encode('utf-8')))
                s = """{{"type": "Att", "arrived": "true", "child_id": "{}", "gender":"{}", "child_name": "{}"}}""".format(*tu)
                data[r_id] = s
            try:
                result = x.json_request(registration_ids=regs_ids, data=data)
            except GCMException as e:
                result = e

        return result

    @staticmethod
    def send_not_arriving_att_to_parents(data_json):
        """ get a list of children ids, retrieve reg. ids and send an un arriving message """
        # get list of children ids of given kindergarten
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        all_childs_ids = Child.get_children_in_KG_id(given_KG_id)
        childs_ids_not_arrived = []
        for c in all_childs_ids:
            d = {"child_id": c, "date": data.get("date")}
            d_j = json.dumps(d)
            if(Att.get_att_of_child_by_child_id_and_date(d_j) == -1):
                childs_ids_not_arrived.append(c)
        x = GCM2(API_KEY, "https://android.googleapis.com/gcm/send")

        value = GCM.get_reg(childs_ids_not_arrived)
        regs_ids = value[0]
        parents_no_regs_ids = value[1]
        data2 = {}
        if regs_ids is not None:
            for r_id in regs_ids:
                c_id = GCM.get_child_id_by_reg_id(reg_id_given=r_id, given__KG_id=given_KG_id)
                # c_id = regs_ids[r_id]
                info_j = Child.get_child_info(c_id)
                c_info = json.loads(info_j)
                tu = (c_id, c_info.get("gender"), (c_info.get("first_name").encode('utf-8')))
                s = """{{"type": "Att", "arrived": "false", "child_id": "{}", "gender":"{}", "child_name": "{}"}}""".format(*tu)
                data2[r_id] = s
            try:
                result = x.json_request(registration_ids=regs_ids, data=data2)
            except GCMException as e:
                result = e

        if parents_no_regs_ids is not None:
            GCM.send_email_for_parents_not_arrived(parents_no_regs_ids)
        return result

    @staticmethod
    def send_new_message_to_parents(data_json):
        """ get a list of children ids, retrieve reg. ids and send a message """
        # get list of children ids of given kindergarten
        data = json.loads(data_json)
        given_KG_id = data.get("KG_id")
        given_msg_key = data.get("MSG_key")


        x = GCM2(API_KEY, "https://android.googleapis.com/gcm/send")
        ent = ndb.Key(Message, int(given_msg_key)).get()

        if ent.public_msg:
            childs_ids = Child.get_children_in_KG_id(given_KG_id)
            value = GCM.get_reg(childs_ids)
            regs_ids = value[0]
            parents_no_regs_ids = value[1]
        else:
            childs_ids = []
            childs_ids = ent.recips.split(',')
            value = GCM.get_reg(childs_ids)
            regs_ids = value[0]
            parents_no_regs_ids = value[1]


        data = {}
        if regs_ids is not None:
            for r_id in regs_ids:
                c_id = GCM.get_child_id_by_reg_id(reg_id_given=r_id, given__KG_id=given_KG_id)
                if (c_id == -1):
                    return -1
                # c_id = regs_ids[r_id]
                info_j = Child.get_child_info(c_id)
                c_info = json.loads(info_j)
                tu = (ent.title.encode('utf-8'), (c_info.get("first_name").encode('utf-8')), str(ent.date))
                s = """{{"type": "MB", "title": "{}", "child_name": "{}", "date": "{}"}}""".format(*tu)
                data[r_id] = s
            try:
                result = x.json_request(registration_ids=regs_ids, data=data)
            except GCMException as e:
                return e
            ent.has_sent = True
        if parents_no_regs_ids is not None:
            GCM.send_message_via_mail(parents_no_regs_ids, ent.title, ent.msg)
        return result

    @staticmethod
    def get_child_id_by_reg_id(reg_id_given, given__KG_id):
        """ Return a child id of reg. id with given KG id """
        ent = GCM.query(GCM.reg_id == reg_id_given).get()
        parent_id_given = ent.parent_id
        parent_childs = PC.get_children_by_parent_mail_address(parent_email_address=parent_id_given)
        for parent_child_id in parent_childs:
            ds = Child.get_child_info(parent_child_id)
            d = json.loads(ds)
            if(d.get("KG_id") == given__KG_id):
                return parent_child_id
        return -1

    @staticmethod
    def get_reg_id_by_parent_email_address_in_json(data_json):
        """ Return a reg id of given parent email address """
        data = json.loads(data_json)
        parent_id_given = data.get("parent_email_address")
        ent = GCM.query(GCM.parent_id == parent_id_given).get()
        if(ent != None):
            return ent.reg_id
        return -1

    @staticmethod
    def send_auto_arriving_mail(mail_address,child_id):
        """ Send a automatic 'arriving' mail for given mail address """
        mail.send_mail(sender="סמארט גן <smart.gan.team@gmail.com>",
                  to=mail_address,
                  subject="Your child arrived to kindergarten",
                  body="""
                        Hello

                        Your child arrived to kindergarten.


                        Have a nice day,
                        Smart Gan Team


                        This is an automatic mail.
                        """)

        mail.send_mail(sender="סמארט גן <smart.gan.team@gmail.com>",
                  to=mail_address,
                  subject="Your child doesnt arrived to kindergarten!!!",
                  body="""
                        Hello

                        Your child doesnt arrived to kindergarten.


                        Have a nice day,
                        Smart Gan Team


                        This is an automatic mail.
                        """)


    @staticmethod
    def send_email_for_parents(parents_no_regs_ids):
        """ send automatic 'arriving' email for parents without android phone """
        for p in parents_no_regs_ids.keys():
            GCM.send_auto_arriving_mail(p, parents_no_regs_ids[p])

    @staticmethod
    def send_email_for_parents_not_arrived(parents_no_regs_ids):
        """ send automatic 'arriving' email for parents without android phone """
        for p in parents_no_regs_ids.keys():
            GCM.send_auto_not_arriving_mail(p, parents_no_regs_ids[p])


    @staticmethod
    def send_auto_new_message_mail(mail_address, child_id, title, msg):
        """ Send a automatic mail with message for given mail address """

    @staticmethod
    def send_message_via_mail(parents_no_regs_ids, title, msg):
        """ send automatic email with message from teacher for parents without android phone """
        for p in parents_no_regs_ids.keys():
            GCM.send_auto_new_message_mail(p, parents_no_regs_ids[p], title=title, msg=msg)